package com.jacobson.core.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import androidx.core.app.ActivityOptionsCompat
import android.util.TypedValue
import android.view.View
import android.view.WindowManager
import androidx.fragment.app.Fragment
import com.jacobson.core.base.BaseActivity


/**
 * ================================================
 *
 * @author Wucz on 2018/7/16 17:47
 * ================================================
 */

object AppUtils {
    fun startActivityForResult(activity: Activity?, clazz: Class<out Activity>, requestCode: Int, applyOptions: ((bundle: Bundle) -> Unit)? = null) {
        activity?.run {
            startActivityForResult(Intent(this, clazz).apply {
                applyOptions?.let {
                    this.putExtras(Bundle().apply { applyOptions(this) })
                }
            }, requestCode)
        }
    }

    fun startActivityForResult(fragment: Fragment?, clazz: Class<out Activity>, requestCode: Int, applyOptions: ((bundle: Bundle) -> Unit)? = null) {
        fragment?.run {
            startActivityForResult(Intent(this.activity, clazz).apply {
                applyOptions?.let {
                    this.putExtras(Bundle().apply { applyOptions(this) })
                }
            }, requestCode)
        }
    }

    fun startActivity(context: Context?, clazz: Class<out Activity>, applyOptions: ((bundle: Bundle) -> Unit)? = null) {
        context?.run {
            startActivity(Intent(this, clazz).apply {
                applyOptions?.let {
                    this.putExtras(Bundle().apply { applyOptions(this) })
                }
            })
        }
    }

    fun startActivity(context: Context?, clazz: Class<out Activity>, activityOptionsCompat: ActivityOptionsCompat, applyOptions: ((bundle: Bundle) -> Unit)? = null) {
        context?.run {
            startActivity(Intent(this, clazz).apply {
                applyOptions?.let {
                    this.putExtras(Bundle().apply { applyOptions(this) })
                }
            }, activityOptionsCompat.toBundle())
        }
    }

    fun getStatusBarHeight(context: Context?): Int {
        return context?.resources?.run {
            val resId = getIdentifier("status_bar_height", "dimen", "android")
            return if (resId > 0) {
                getDimensionPixelSize(resId)
            } else {
                getDefaultStatusBarHeight()
            }
        } ?: getDefaultStatusBarHeight()
    }

    private fun getDefaultStatusBarHeight(): Int {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                24f, Resources.getSystem().displayMetrics).toInt()
    }

    fun getNavigationBarHeight(context: Context?): Int {
        val resourceId = context!!.resources.getIdentifier("navigation_bar_height", "dimen", "android")
        return context.resources.getDimensionPixelSize(resourceId)
    }

    //判断是否存在NavigationBar
    @SuppressLint("PrivateApi")
    fun checkDeviceHasNavigationBar(context: Context): Boolean {
        var hasNavigationBar = false
        val rs = context.resources
        val id = rs.getIdentifier("config_showNavigationBar", "bool", "android")
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id)
        }
        try {
            val systemPropertiesClass = Class.forName("android.os.SystemProperties")
            val m = systemPropertiesClass.getMethod("get", String::class.java)
            val navBarOverride = m.invoke(systemPropertiesClass, "qemu.hw.mainkeys") as String
            if ("1" == navBarOverride) {
                hasNavigationBar = false
            } else if ("0" == navBarOverride) {
                hasNavigationBar = true
            }
        } catch (e: Exception) {

        }
        return hasNavigationBar
    }

    /**
     * 状态栏浅色模式
     * 设置状态栏黑色文字、图标
     * 适配4.4以上版本Miui、Flyme和6.0以上版本其他Android
     */
    fun setStatusBarLightMode(activity: Activity): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //如果是6.0以上将状态栏文字改为黑色
            activity.window.run {
                decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN.or(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
            }
            return true
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //大于4.4小于6.0，判断是否为小米或魅族手机，如果是则将状态栏文字改为黑色
            return setMIUIStatusBarMode(activity, false) || setFLYMEStatusBarLightMode(activity, false)
        }
        return false
    }

    fun setStatusBarDarkMode(activity: Activity): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //如果是6.0以上将状态栏文字改为白色
            activity.window.run {
                decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN.or(View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
            }
            return true
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //大于4.4小于6.0，判断是否为小米或魅族手机，如果是则将状态栏文字改为浅色
            return setMIUIStatusBarMode(activity, true) || setFLYMEStatusBarLightMode(activity, true)
        }
        return false
    }

    /**
     * 设置FLYME状态栏色调模式
     * @param activity 当前ACTIVITY
     * @param isDarkMode 是否是深色调模式，false-浅色调模式：文字图标深色， true-深色调模式：文字图标浅色
     * @return true-设置成功，false-失败
     */
    private fun setFLYMEStatusBarLightMode(activity: Activity, isDarkMode: Boolean): Boolean {
        var result = false
        activity.window?.let {
            try {
                val lp = it.attributes
                val darkFlag = WindowManager.LayoutParams::class.java.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON")
                val meiZuFlags = WindowManager.LayoutParams::class.java.getDeclaredField("meizuFlags")
                darkFlag.isAccessible = true
                meiZuFlags.isAccessible = true
                val bit = darkFlag.getInt(null)
                val value = meiZuFlags.getInt(lp) or if (isDarkMode) bit.inv() else bit
                meiZuFlags.setInt(lp, value)
                it.attributes = lp
                result = true
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return result
    }

    /**
     * 设置MIUI状态栏色调模式
     * 需要MIUI V6以上
     * @param activity 当前ACTIVITY
     * @param isDarkMode 是否是深色调模式，false-浅色调模式：文字图标深色， true-深色调模式：文字图标浅色
     * @return true-设置成功，false-失败
     */
    @SuppressLint("PrivateApi")
    private fun setMIUIStatusBarMode(activity: Activity, isDarkMode: Boolean): Boolean {
        var result = false
        activity.window?.javaClass?.let {
            try {
                val darkModeFlag: Int
                val layoutParams = Class.forName("android.view.MiuiWindowManager\$LayoutParams")
                val field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE")
                darkModeFlag = field.getInt(layoutParams)
                val extraFlagField = it.getMethod("setExtraFlags", Int::class.java, Int::class.java)
                extraFlagField.invoke(activity.window, if (isDarkMode) 0 else darkModeFlag, darkModeFlag)
                result = true
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return result
    }

    fun getDrawable(context: Context?, resId: Int): Drawable? =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                context?.getDrawable(resId)
            } else {
                context?.resources?.getDrawable(resId)
            }

    fun setResult(activity: BaseActivity, applyParameters: ((bundle: Bundle) -> Unit)? = null) {
        val bundle = Bundle()
        applyParameters?.invoke(bundle)
        val intent = Intent()
        intent.putExtras(bundle)
        activity.setResult(Activity.RESULT_OK, intent)
        activity.finish()
    }

}